package cn.cdeden.aiqa.service.impl;

import cn.cdeden.common.core.constant.CacheNames;
import cn.cdeden.common.core.constant.UserConstants;
import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.common.redis.utils.CacheUtils;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import cn.cdeden.aiqa.domain.bo.SysKnowledgeConfigBo;
import cn.cdeden.aiqa.domain.vo.SysKnowledgeConfigVo;
import cn.cdeden.aiqa.domain.SysKnowledgeConfig;
import cn.cdeden.aiqa.mapper.SysKnowledgeConfigMapper;
import cn.cdeden.aiqa.service.ISysKnowledgeConfigService;
import cn.cdeden.common.core.utils.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 知识库配置11Service业务层处理
 *
 * @author Nick
 * @date 2024-12-06
 */
@RequiredArgsConstructor
@Service
public class SysKnowledgeConfigServiceImpl implements ISysKnowledgeConfigService {

    private final SysKnowledgeConfigMapper baseMapper;

    // 根据 configKey 获取 configValue
    @Override
    public String getConfigValueByKey(String configKey) {
        // 构造查询条件
        LambdaQueryWrapper<SysKnowledgeConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysKnowledgeConfig::getConfigKey, configKey);

        // 查询单条记录
        SysKnowledgeConfig config = baseMapper.selectOne(queryWrapper);
        return config != null ? config.getConfigValue() : null;
    }

    // 获取所有 configKey 对应的 configValue
    @Override
    public List<SysKnowledgeConfig> getAllConfigs() {
        return baseMapper.selectList(null); // 查询所有记录
    }

    // 根据 configValue 获取所有 configKey
    @Override
    public List<String> getConfigKeysByValue(String configValue) {
        LambdaQueryWrapper<SysKnowledgeConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysKnowledgeConfig::getConfigValue, configValue);

        // 获取所有符合条件的记录
        List<SysKnowledgeConfig> configs = baseMapper.selectList(queryWrapper);
        return configs.stream()
            .map(SysKnowledgeConfig::getConfigKey)  // 获取所有 configKey
            .collect(Collectors.toList());
    }

    /**
     * 查询知识库配置
     *
     * @param id 主键
     * @return 知识库配置
     */
    @Override
    public SysKnowledgeConfigVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询知识库配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 知识库配置分页列表
     */
    @Override
    public TableDataInfo<SysKnowledgeConfigVo> queryPageList(SysKnowledgeConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysKnowledgeConfig> lqw = buildQueryWrapper(bo);
        Page<SysKnowledgeConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的知识库配置列表
     *
     * @param bo 查询条件
     * @return 知识库配置列表
     */
    @Override
    public List<SysKnowledgeConfigVo> queryList(SysKnowledgeConfigBo bo) {
        LambdaQueryWrapper<SysKnowledgeConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysKnowledgeConfig> buildQueryWrapper(SysKnowledgeConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysKnowledgeConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getConfigName()), SysKnowledgeConfig::getConfigName, bo.getConfigName());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysKnowledgeConfig::getConfigKey, bo.getConfigKey());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigValue()), SysKnowledgeConfig::getConfigValue, bo.getConfigValue());
        lqw.eq(bo.getUpdatedAt() != null, SysKnowledgeConfig::getUpdatedAt, bo.getUpdatedAt());
        return lqw;
    }

    /**
     * 新增知识库配置
     *
     * @param bo 知识库配置
     * @return 是否新增成功
     */
    @Override
    @CachePut(cacheNames = CacheNames.KNOWLEDGE_CONFIG, key = "#bo.configKey")
    public Boolean insertByBo(SysKnowledgeConfigBo bo) {
        SysKnowledgeConfig add = MapstructUtils.convert(bo, SysKnowledgeConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改知识库配置
     *
     * @param bo 知识库配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysKnowledgeConfigBo bo) {
        SysKnowledgeConfig update = MapstructUtils.convert(bo, SysKnowledgeConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysKnowledgeConfig entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除知识库配置信息
     *
     * @param configIds     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> configIds, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long configId : configIds) {
            SysKnowledgeConfig config = baseMapper.selectById(configId);

            CacheUtils.evict(CacheNames.KNOWLEDGE_CONFIG, config.getConfigKey());
        }
        baseMapper.deleteByIds(Arrays.asList(configIds));
        return true;
    }

    @Override
    @Cacheable(cacheNames = CacheNames.KNOWLEDGE_CONFIG, key = "#configKey")
    public String selectConfigByKey(String configKey) {
        SysKnowledgeConfig retConfig = baseMapper.selectOne(new LambdaQueryWrapper<SysKnowledgeConfig>()
            .eq(SysKnowledgeConfig::getConfigKey, configKey));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    @CachePut(cacheNames = CacheNames.KNOWLEDGE_CONFIG, key = "#bo.configKey")
    public String updateConfig(SysKnowledgeConfigBo bo) {
        int row = 0;
        SysKnowledgeConfig config = MapstructUtils.convert(bo, SysKnowledgeConfig.class);
        if (config.getId() != null) {
            SysKnowledgeConfig temp = baseMapper.selectById(config.getId());
            if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
                CacheUtils.evict(CacheNames.KNOWLEDGE_CONFIG, temp.getConfigKey());
            }
            row = baseMapper.updateById(config);
        } else {
            CacheUtils.evict(CacheNames.KNOWLEDGE_CONFIG, config.getConfigKey());
            row = baseMapper.update(config, new LambdaQueryWrapper<SysKnowledgeConfig>()
                .eq(SysKnowledgeConfig::getConfigKey, config.getConfigKey()));
        }
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }
}
